#!/usr/bin/python
# -*- coding: utf-8 -*-

######################################
#                                    #
# plugin.video.xbmcberry for xbmc    #
# author: t0mus                      #
#                                    #
######################################

""" XBMC plugin xbmcberry """

import os
import sys
import xbmc
import xbmcaddon
import xbmcplugin
import xbmcgui
import urllib2
import socket

__this_plugin__ = int(sys.argv[1])
host='http://xbmcberry.appspot.com'
#host='http://localhost:8080'
reload(sys)
sys.setdefaultencoding('utf-8')

__addon__ = 'plugin.video.xbmcberry'
__settings__ = xbmcaddon.Addon(id=__addon__)
__plugin_string__ = 'plugin://' + __addon__ + '/?'

__images_dir__ = \
    xbmc.translatePath(os.path.join(__settings__.getAddonInfo('path'),
                       'resources', 'images'))
__lib_dir__ = \
    xbmc.translatePath(os.path.join(__settings__.getAddonInfo('path'),
                       'resources', 'lib'))

sys.path.append(__lib_dir__)

from strings import __header_string__
from common_strings import __categories_string__, __search_string__, \
    __loadingcategories_string__, \
    __movietitle_string__, __loadingmovies_string__, __nextpage_string__

from t0mus.common.common import *
from BeautifulSoup import BeautifulSoup

class TOOLS(object):
    """ Parameters handling tools."""
    def __init__(self):
        self.cmds = {}

    def load_parameters(self, params):
        """ Loads parameters."""
        self.cmds = {}
        split_cmds = params[params.find('?') + 1:].split('&')
        for cmd in split_cmds:
            if len(cmd) > 0:
                split_cmd = cmd.split('=')
                name = split_cmd[0]
                value = split_cmd[1]
                self.cmds[name] = value

    def get_cmd(self, cmd):
        """ Returns command."""
        if cmd in self.cmds:
            return self.cmds[cmd]
        else:
            return None

__tools__ = TOOLS()
__tools__.load_parameters(sys.argv[2])
__get__ = __tools__.get_cmd

def open_url(url):
    """ Opens url using urllib2."""

    try:
        socket.setdefaulttimeout(int(float(__settings__.getSetting('net.timeout'))))
        request = urllib2.Request(url)
        request.add_header('Referer',url)
        return urllib2.urlopen(request)
    except IOError as io_error:
        print('network error (',io_error,') while opening '+url)

def create_main_menu():
    """ Creates main menu."""

    browse = xbmcgui.ListItem(__categories_string__,
                              iconImage=os.path.join(__images_dir__,
                              'Folder 2.png'),
                              thumbnailImage=os.path.join(__images_dir__,
                              'Folder 2.png'))
    search = xbmcgui.ListItem(__search_string__,
                              iconImage=os.path.join(__images_dir__,
                              'Folder 2 Search.png'),
                              thumbnailImage=os.path.join(__images_dir__,
                              'Folder 2 Search.png'))
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'browse=true', browse, isFolder=True)
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'search=true', search, isFolder=True)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)


class Movie:
    def __init__(self, name, link):
        self.name = unescape(name)
        self.link = link


class Category:
    def __init__(self, name, links):
        self.name = name
        self.links = links

def create_main_menu():
    """ Creates main menu."""

    browse = xbmcgui.ListItem(__categories_string__,
                              iconImage=os.path.join(__images_dir__,
                              'Folder 2.png'),
                              thumbnailImage=os.path.join(__images_dir__,
                              'Folder 2.png'))
    search = xbmcgui.ListItem(__search_string__,
                              iconImage=os.path.join(__images_dir__,
                              'Folder 2 Search.png'),
                              thumbnailImage=os.path.join(__images_dir__,
                              'Folder 2 Search.png'))
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'browse=true', browse, isFolder=True)
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'search=true', search, isFolder=True)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)


def create_categories():
    """ Creates categories menu."""

    dialog = xbmcgui.DialogProgress()
    dialog.create(__header_string__, __loadingcategories_string__)
    count = 0
    soup = BeautifulSoup(open_url(host+'/categories').read())    
    for cat in soup.find('ul','categories').findAll('li','category'):
        list_item = xbmcgui.ListItem(cat.string)
        xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                    + 'category=' + str(count), list_item,
                                    isFolder=True)
        count = count + 1
        dialog.update(count, __loadingcategories_string__)
    dialog.close()
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)

def addMovies(link,__page__):
    dialog = xbmcgui.DialogProgress()
    dialog.create(__header_string__, __loadingmovies_string__)
    dialog.update(0, __loadingmovies_string__)
    soup = BeautifulSoup(open_url(link).read())
    dialog.update(100, __loadingmovies_string__)
    count=0
    for li in soup.find('ul','movies').findAll('li','movie'):
        anchor = li.find('a','link')
        try:
            add(Movie(anchor.string[::-1],anchor['href'][::-1]))
        except:
            add(Movie('error',''))
        count=count+1
    dialog.close()
    return count

def addNextPage(current):
    next=current+1
    results = int(float(__settings__.getSetting('ui.results')))
    start = current*results
    stop = start + results
    list_item = xbmcgui.ListItem(__nextpage_string__ + ' (' + str(start+1) + ' - ' + str(stop)+ ')')
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'category=' + __get__('category')
                                + '&page=' + str(next),
                                list_item, isFolder=True)

def add(movie):
    name=movie.name
    link=movie.link
    list_item = xbmcgui.ListItem(name)
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'movie=' + link+'&name='+name, list_item,
                                isFolder=True)
def compute_mask():
    mask=0
    if (__settings__.getSetting('sites.a33')=='true'):
        mask=mask+128
    if (__settings__.getSetting('sites.pecetowiec')=='true'):
        mask=mask+64
    if (__settings__.getSetting('sites.kinolive')=='true'):
        mask=mask+32
    if (__settings__.getSetting('sites.megustavid')=='true'):
        mask=mask+16
    if (__settings__.getSetting('sites.osiu')=='true'):
        mask=mask+8
    if (__settings__.getSetting('sites.seans-online')=='true'):
        mask=mask+4
    return str(mask)
from t0mus.common.hosting import recognize_video_hosting
if __get__('category') != None:
    if __get__('page') != None:
        __page__ = int(__get__('page'))
    else:
        __page__ = 1
    count=addMovies(host+'/?mask='+compute_mask()+'&category='+__get__('category')+'&results='+str(int(float(__settings__.getSetting('ui.results'))))+'&page='+str(__page__),__page__)
    if count==int(float(__settings__.getSetting('ui.results'))):
        addNextPage(__page__)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)
elif __get__('movie') != None:
    __movie__ = str(__get__('movie'))
    __item_name__ = str(__get__('name'))
    recognize_video_hosting(__this_plugin__, __movie__, __item_name__)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)
elif __get__('browse') != None:
    create_categories()
elif __get__('search') != None:
    __text__ = None
    if __get__('query') != None:
        __text__ = __get__('query')
    else:
        __kb__ = xbmc.Keyboard('', __movietitle_string__, False)
        __kb__.doModal()
        if __kb__.isConfirmed():
            __text__ = __kb__.getText()

    if __text__ != None:
        if __get__('page') != None:
            __page__ = int(__get__('page'))
        else:
            __page__ = 1

    __count__ = addMovies(host+'/?mask='+compute_mask()+'&query='+__text__+'&results='+str(int(float(__settings__.getSetting('ui.results'))))+'&page='+str(__page__),__page__)
    results = int(float(__settings__.getSetting('ui.results')))
    if __count__ == results:
        __nextp__ = __page__ + 1
        __nextPage__ = create_next_page_list_item(__page__,
                __count__, results)
        xbmcplugin.addDirectoryItem(__this_plugin__,
                __plugin_string__ + 'search=true&query=' + __text__
                + '&page=' + str(__nextp__), __nextPage__,
                isFolder=True)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)
else:
    create_main_menu()
